import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Grid,
  TextField,
  InputAdornment,
  CircularProgress,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import { useSearchParams } from 'react-router-dom';
import { Implementation } from '../types';
import { api } from '../services/api';
import ImplementationCard from '../components/CodeImplementation/ImplementationCard';

const SearchPage: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '');
  const [results, setResults] = useState<Implementation[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const query = searchParams.get('q');
    if (query) {
      setSearchQuery(query);
      performSearch(query);
    }
  }, [searchParams]);

  const performSearch = async (query: string) => {
    setLoading(true);
    try {
      const searchResults = await api.searchImplementations(query);
      setResults(searchResults);
    } catch (error) {
      console.error('Error searching implementations:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter' && searchQuery.trim()) {
      setSearchParams({ q: searchQuery.trim() });
    }
  };

  return (
    <Container>
      {/* 搜索框 */}
      <Box sx={{ my: 4 }}>
        <TextField
          fullWidth
          variant="outlined"
          placeholder="搜索技术实现..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          onKeyPress={handleSearch}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />
      </Box>

      {/* 搜索结果 */}
      <Box sx={{ my: 4 }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <CircularProgress />
          </Box>
        ) : (
          <>
            <Typography variant="h6" gutterBottom>
              搜索结果 ({results.length})
            </Typography>
            <Grid container spacing={3}>
              {results.map((implementation) => (
                <Grid item xs={12} sm={6} md={4} key={implementation.id}>
                  <ImplementationCard implementation={implementation} />
                </Grid>
              ))}
              {results.length === 0 && searchParams.get('q') && (
                <Grid item xs={12}>
                  <Typography variant="body1" color="text.secondary" align="center">
                    未找到相关实现
                  </Typography>
                </Grid>
              )}
            </Grid>
          </>
        )}
      </Box>
    </Container>
  );
};

export default SearchPage;
